package org.qhhc.thread.endthread;

public class ExitFlagTest {
    // volatile 修饰符用来保证其他线程读取的时候总是该变量的最新的值
    private volatile boolean exitFlag = false;

    public void run(){
        while (!exitFlag) {
            System.out.println("Thread is running...");
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 设置中断状态
            }
        }
        System.out.println("Thread is exiting...");
    }
    public void stop(){
        exitFlag = true; // 设置退出标志位true
    }

    public static void main(String[] args) throws InterruptedException {
        ExitFlagTest test = new ExitFlagTest();
        Thread thread = new Thread(test::run);
        thread.start();
        thread.sleep(5000);
        test.stop();
    }
}
